package com.anhry.app.safety.manage.oa.struts.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.anhry.app.safety.manage.oa.bean.TbCorpMsg;
import com.anhry.app.safety.manage.oa.bean.TbCorpMsgFj;
import com.anhry.app.safety.manage.oa.struts.base.OABaseAction;
import com.anhry.app.safety.manage.system.bean.TbUser;
import com.anhry.app.safety.util.Loggers;
import com.anhry.app.safety.util.Page;
import com.anhry.app.safety.util.UploadFile;
import com.anhry.app.safety.util.Util;
import com.anhry.app.safety.util.UtilMethod;
import com.anhry.app.safety.util.bean.Permission;

/**
 * 企业在线帮助类
 * @author zhangpeng
 * @date 2012-09-27
 */
@Controller
@Scope("prototype")
@SuppressWarnings("unchecked")
public class CorpHelpAction extends OABaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String tableType; // 0，公告通知 1，在线帮助

	private String search; // 是否解码查询关键字 1解码

	private String keyWord; // 搜索关键字

	private String beginDate; // 开始时间

	private String endDate; // 结束时间

	private List msgList; //

	private List<TbCorpMsgFj> msgFjList;

	private TbCorpMsg tbCorpMsg;

	private String msgId; // 消息ID

	private TbCorpMsgFj tbCorpMsgFj;

	private String fjId; // 附件ID

	private String[] docFileName;// 选择的文件名

	private File[] doc;

	private String file; // 需要下载的文件名,通过链接传过来

	private String fName;

	private String filePath;

	private String suffix; // 后缀名

	private String ids; // 删除多条传过来的id数组
	
	private String newsContent;
	
	private String userName;

	/**
	 * 列表方法
	 * 
	 * @return
	 */
	@Permission(module = "corpHelp", permissionVaule = 1)
	public String list() {
		try {
			int num = 1; // 初始页码
			int rowCount = 0; // 记录总数
			int size = 10; // 定义分页的每页显示的初始个数
			if (super.num != null && !"".equals(super.num)) {
				num = Integer.parseInt(super.num);
			}
			if (super.size != null && !"".equals(super.size)) {
				size = Integer.parseInt(super.size);
			}
			checkSearch();
			StringBuffer hqlString = new StringBuffer("select count(*) from Tb_Corp_Msg m left join tb_user u on m.user_id = u.id where 1=1");
			if (!"".equals(beginDate) && beginDate != null) {
				hqlString.append(" and m.msg_Date >= to_date('").append(beginDate).append("','yyyy-MM-dd')");
			}
			if (!"".equals(endDate) && endDate != null) {
				hqlString.append(" and m.msg_Date <= to_date('").append(endDate).append("','yyyy-MM-dd')");
			}
			if (!"".equals(keyWord) && keyWord != null) {
				hqlString.append(" and m.msg_Title like '%").append(keyWord).append("%'");
			}
			hqlString.append(" and m.msg_Type = ").append(tableType);
			List list = this.utilService.getObjectBySql(hqlString.toString(),0,0);
			
			if (list != null && Integer.parseInt(list.get(0)+"")>0) {
				int resultCou = Integer.parseInt(list.get(0)+"");
				Page page = new Page(size, num, resultCou);
				this.setPage(page);
				msgList = this.utilService.getObjectBySql(hqlString.toString().replace("select count(*) ", "select m.id, m.msg_title, m.msg_date,u.user_Name "), page.getStartRow(), page.getSize());
			}
			result = "corp_help_list";
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("manage CorpMsgAction:list()出错" + e);
		}
		tip = "加载出错！";
		return ERROR;
	}

	/**
	 * 加载添加页面
	 * 
	 * @return
	 */
	@Permission(module = "corpHelp", permissionVaule = 0)
	public String loadAdd() {
		try {
			checkSearch();
			result = "corp_help_add";
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("manage CorpMsgAction:loadAdd()出错" + e);
		}
		tip = "打开添加页面出错";
		return ERROR;
	}

	/**
	 * 添加通知/帮助 和 附件
	 * 
	 * @return
	 */
	@Permission(module = "corpHelp", permissionVaule = 0)
	public String add() {
		try {
			TbUser user = (TbUser) this.contextPvd.getSessionAttr(Util.SESSION_ADMINUSER);
			tbCorpMsg.setIsClock("0");
			tbCorpMsg.setMsgDate(new Date());
			tbCorpMsg.setMsgType(tableType);
			tbCorpMsg.setUserId(user.getId());
			tbCorpMsg.setMsgContent(newsContent);
			this.utilService.save(tbCorpMsg);
			// 有附件上传
			if (!"".equals(docFileName) && docFileName != null) {
				String path = Util.SAFETY_FILE + File.separator + Util.FILE_FOLDER + File.separator + Util.OA_MSG;
				for (int i = 0; i < doc.length; i++) {
					String fileName = upLoadFile(doc[i], path, docFileName[i]);// 上传附件
					String path1 = Util.FILE_FOLDER + File.separator + Util.OA_MSG + File.separator + fileName;
					tbCorpMsgFj = new TbCorpMsgFj();
					tbCorpMsgFj.setFjPath(path1);
					tbCorpMsgFj.setFjSize(UtilMethod.getFjSize(doc[i].length() + ""));
					tbCorpMsgFj.setFjTitle(docFileName[i]);
					tbCorpMsgFj.setFjType(this.suffix);
					tbCorpMsgFj.setIsDele("0");
					tbCorpMsgFj.setMsgId(tbCorpMsg.getId());
					this.utilService.save(tbCorpMsgFj);
				}
			}
			tip = "上传成功！";
			return list();
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("manage CorpMasAction:add()出错" + e);
		}
		tip = "添加失败！";
		return ERROR;
	}

	/**
	 * 上传文件
	 */
	public String upLoadFile(File file, String dst, String fileName) {
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
		String name = "";
		if (checkSuffix(suffix)) {// 判断后缀
			name = UploadFile.copy2(file, dst, fileName);
			return name;
		} else {
			tip = "文件格式非法！";
			return "";
		}
	}

	/**
	 * 检查后缀名是否合法
	 */
	public boolean checkSuffix(String suffix) {
		// 合法后缀名
		String suf = "jpg,png,bmp,html,htm,doc,xls,ppt";
		if (!"".equals(suf)) {
			String[] sufs = suf.split(",");
			for (String s : sufs) {
				if (suffix.toLowerCase().equals(s)) {
					this.suffix = suffix;
					return true;
				}
			}
			return false;
		}
		return true;
	}

	/**
	 * 按ID删除
	 */
	@Permission(module = "corpHelp", permissionVaule = 3)
	public String delete() {
		try {
			this.checkSearch();// 检查是否解码
			search = "1";
			if (!"".equals(ids) && ids != null) {
				String hqlString = "from TbCorpMsg m where m.id in (" + ids + ")";
				List<TbCorpMsg> msgList = (List<TbCorpMsg>) this.utilService.getHqlQuery(hqlString);
				for (TbCorpMsg msg : msgList) {
					this.utilService.delete(msg);
					deleteFj(msg.getId() + "");
				}
				tip = "删除成功";
				return list();
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("manager:CorpMsgAction delete()出错" + e);
		}
		tip = "删除失败";
		return ERROR;
	}

	/**
	 * 删除附件
	 * 
	 * @param msgId
	 * @return
	 */
	@Permission(module = "corpHelp", permissionVaule = 3)
	public boolean deleteFj(String msgId) {
		try {
			List<TbCorpMsgFj> fjList = (List<TbCorpMsgFj>) this.utilService.getHqlQuery("from TbCorpMsgFj f where f.msgId = " + msgId);
			if (fjList.size()>0){
				for (TbCorpMsgFj fj : fjList) {
					fj.setIsDele("1");
					this.utilService.update(fj);
				}
			} else {
				return true;
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 加载数据
	 * 
	 * @return
	 */
	public String loadMsg() {
		try {
			checkSearch();// 检查是否解码
			if (!"".equals(msgId) && msgId != null) {
				tbCorpMsg = (TbCorpMsg) this.utilService.getObjectById(TbCorpMsg.class,Long.parseLong(msgId));
				msgFjList = (List<TbCorpMsgFj>) this.utilService.getHqlQuery("from TbCorpMsgFj f where f.msgId = " + tbCorpMsg.getId()+" and f.isDele=0");
				newsContent = tbCorpMsg.getMsgContent();
				return SUCCESS;
			}
			//加载后的页面由上一页面指定
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("manage CorpMsgAction:loadMsg()出错！" + e);
		}
		tip = "加载出错！";
		return ERROR;
	}

	@Permission(module = "corpHelp", permissionVaule = 2)
	public String editMsg() {
		try {
			checkSearch();
			TbUser user = (TbUser) this.contextPvd.getSessionAttr(Util.SESSION_ADMINUSER);
			// 修改TbCorpMsg表
			TbCorpMsg msg = (TbCorpMsg) this.utilService.getObjectById(TbCorpMsg.class, Long.parseLong(msgId));
			if (msg != null) {
				msg.setMsgContent(newsContent);
				msg.setMsgDate(new Date());
				msg.setMsgTitle(tbCorpMsg.getMsgTitle());
				msg.setUserId(user.getId());
				this.utilService.update(msg);
			}
			// 修改附件表
			if (!"".equals(docFileName) && docFileName != null) {
				String path = Util.SAFETY_FILE + File.separator + Util.FILE_FOLDER + File.separator + Util.OA_MSG;
				for (int i = 0; i < doc.length; i++) {
					tbCorpMsgFj = new TbCorpMsgFj();
					String fileName = upLoadFile(doc[i], path, docFileName[i]);// 上传附件
					String path1 = Util.FILE_FOLDER + File.separator + Util.OA_MSG + File.separator + fileName;
					tbCorpMsgFj.setFjPath(path1);
					tbCorpMsgFj.setFjSize(UtilMethod.getFjSize(doc[i].length() + ""));
					tbCorpMsgFj.setFjTitle( docFileName[i]);
					tbCorpMsgFj.setFjType(this.suffix);
					tbCorpMsgFj.setIsDele("0");
					tbCorpMsgFj.setMsgId(msg.getId());
					this.utilService.save(tbCorpMsgFj);
				}
			}
			tip = "修改成功";
			return list();
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("manage CorpMsgAction:editMsg()出错" + e);
		}
		tip = "编辑失败";
		return ERROR;
	}

	/**
	 * 异步附件删除
	 */
	public void deleFj() {
		this.contextPvd.getResponse().setContentType("charset=UTF-8");
		TbCorpMsgFj fj = null;
		try {
			if (null != fjId && !"".equals(fjId)) {
				fj = (TbCorpMsgFj) this.utilService.getObjectById(TbCorpMsgFj.class, Long.parseLong(fjId));
				if (null != fj) {
					this.utilService.delete(fj);
				}
				this.contextPvd.getResponse().getWriter().write("1");
			} else {
				this.contextPvd.getResponse().getWriter().write("2");
			}
			this.contextPvd.getResponse().getWriter().flush();
			this.contextPvd.getResponse().getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.info("NoticeAction deleFj()方法：" + e);
		}
	}

	/**
	 * 下载
	 * @return
	 */
	public String downLoad() {
		try {
			TbCorpMsgFj f = null;
			if (null != this.fjId && !"".equals(this.fjId)) {
				f = (TbCorpMsgFj) this.utilService.getObjectById(TbCorpMsgFj.class, Long.parseLong(this.fjId));
				if (!"".equals(f.getFjPath()) && f.getFjPath() != null) {
					if (new File(Util.SAFETY_FILE + File.separator + f.getFjPath()).exists()) {
						filePath = f.getFjPath().substring(0, f.getFjPath().lastIndexOf("\\") + 1);
						file = f.getFjPath().substring(f.getFjPath().lastIndexOf("\\") + 1, f.getFjPath().length());
						fName = new String(f.getFjTitle().getBytes("gbk"), "iso-8859-1");
						return SUCCESS;
					} else {
						tip = "对不起，文件已删除或不存在";
						return "nofile";
					}
				}
			}
			tip = "查询文件错误!";
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("manage CorpMsgAction:downLoad()出错!" + e);
		}
		tip = "下载出错！";
		return ERROR;
	}

	/**
	 * 对于上边的文件路径，给出他的输入流(实际文件资源)，对应在配置文件中的InputName属性名
	 */
	public InputStream getInputStream() {
		InputStream o = null;
		try {
			o = new FileInputStream(Util.SAFETY_FILE + File.separator + filePath + file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return o;
	}

	// 解码
	public void checkSearch() {
		if (this.search == null || !"1".equals(this.search)) {
			keyWord = this.contextPvd.decode(this.keyWord);
		}
	}

	public String getBeginDate() {
		return beginDate;
	}

	public void setBeginDate(String beginDate) {
		this.beginDate = beginDate;
	}

	public File[] getDoc() {
		return doc;
	}

	public void setDoc(File[] doc) {
		this.doc = doc;
	}

	public String getEndDate() {
		return endDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public String getFile() {
		return file;
	}

	public void setFile(String file) {
		this.file = file;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public String getFjId() {
		return fjId;
	}

	public void setFjId(String fjId) {
		this.fjId = fjId;
	}

	public String getFName() {
		return fName;
	}

	public void setFName(String name) {
		fName = name;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getKeyWord() {
		return keyWord;
	}

	public void setKeyWord(String keyWord) {
		this.keyWord = keyWord;
	}

	public List<TbCorpMsgFj> getMsgFjList() {
		return msgFjList;
	}

	public void setMsgFjList(List<TbCorpMsgFj> msgFjList) {
		this.msgFjList = msgFjList;
	}

	public String getMsgId() {
		return msgId;
	}

	public void setMsgId(String msgId) {
		this.msgId = msgId;
	}

	public List getMsgList() {
		return msgList;
	}

	public void setMsgList(List msgList) {
		this.msgList = msgList;
	}

	public String getSearch() {
		return search;
	}

	public void setSearch(String search) {
		this.search = search;
	}

	public String getSuffix() {
		return suffix;
	}

	public void setSuffix(String suffix) {
		this.suffix = suffix;
	}

	public String getTableType() {
		return tableType;
	}

	public void setTableType(String tableType) {
		this.tableType = tableType;
	}

	public TbCorpMsg getTbCorpMsg() {
		return tbCorpMsg;
	}

	public void setTbCorpMsg(TbCorpMsg tbCorpMsg) {
		this.tbCorpMsg = tbCorpMsg;
	}

	public TbCorpMsgFj getTbCorpMsgFj() {
		return tbCorpMsgFj;
	}

	public void setTbCorpMsgFj(TbCorpMsgFj tbCorpMsgFj) {
		this.tbCorpMsgFj = tbCorpMsgFj;
	}

	public String[] getDocFileName() {
		return docFileName;
	}

	public void setDocFileName(String[] docFileName) {
		this.docFileName = docFileName;
	}

	public String getNewsContent() {
		return newsContent;
	}

	public void setNewsContent(String newsContent) {
		this.newsContent = newsContent;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

}
